package db;

import base.User;
import java.io.IOException;
import javax.microedition.rms.*;

/**
 * Manages the user information in the local db
 * @author Shayan
 */
public class UserManager {

    private final static String USERS_TABLE = "USERS";

     public static void deleteAll() throws RecordStoreException {
        RecordStore.deleteRecordStore(USERS_TABLE);
    }

    public static void persist(User user)
            throws RecordStoreException, IOException {
        RecordStore rs = RecordStore.openRecordStore(USERS_TABLE, true);

        byte[] data = user.getData();

        int recordId = DatabaseHelper.findRecordId(rs, user.getId());
        if (recordId == -1) {
            rs.addRecord(data, 0, data.length);
        } else {
            rs.setRecord(recordId, data, 0, data.length);
        }

        rs.closeRecordStore();
    }

    public static User getById(String id)
            throws RecordStoreException, IOException {
        RecordStore rs = RecordStore.openRecordStore(USERS_TABLE, true);

        User result = null;
        byte[] data = DatabaseHelper.findRecordById(rs, id);
        if (data != null) {
            result = User.create(data);
        }

        rs.closeRecordStore();
        return result;
    }

    public static User getByName(String name)
            throws RecordStoreException, RecordStoreNotOpenException, InvalidRecordIDException, IOException {
        RecordStore rs = RecordStore.openRecordStore(USERS_TABLE, true);

        User result = null;
        byte[] data = DatabaseHelper.findRecordByName(rs, name);
        if (data != null) {
            result = User.create(data);
        }

        rs.closeRecordStore();
        return result;
    }
}
